package main

import (
	"fmt"
	"sync"
	"time"
)

type concurrentMap struct {
	sync.RWMutex
	mp map[int]int
}

//写加锁
func (c *concurrentMap) Set(key int, value int) {
	c.Lock()
	defer c.Unlock()
	c.mp[key] = value
}

//读加锁
func (c *concurrentMap) Get(key int) int {
	c.RLock()
	defer c.RUnlock()
	return c.mp[key]
}

func main() {
	c := concurrentMap{
		mp: make(map[int]int),
	}

	//go原生的map线程不安全，同时读写会报错,使用sync.RWMutex解决
	go func() {
		for i := 0; i < 10000; i++ {
			c.Set(i, i)
		}
	}()

	go func() {
		for i := 0; i < 10000; i++ {
			res := c.Get(i)
			fmt.Printf("get map:[%d=%d]", i, res)
		}
	}()
	time.Sleep(30 * time.Second)
}
